﻿using System;
using System.Diagnostics.Contracts;
using System.IO;
using System.Diagnostics;
using System.Configuration;
using System.Text.RegularExpressions;

namespace GIMS.Exec
{
    /// <summary>
    /// Class to use execute IM-Skripts with ImageMagick.
    /// </summary>
    public class Executor : IExecutor
    {
        private string tempPath;


        public string CreatePreview(string program, string script)
        {
            string outputPath = GetTempFilePath(".png");
            string completeCommand = string.Concat(script, @" """, outputPath, @""" ");
            ExecuteCommand(program, completeCommand);
            return outputPath;
        }


        public void ExecuteCommand(string program, string script)
        {
            string imPath = ConfigurationManager.AppSettings["IMPath"];
            Contract.Assert(imPath != null);

            var startInfo = new ProcessStartInfo
                                {
                                    FileName = Path.Combine(imPath, program + ".exe"),
                                    UseShellExecute = false,
                                    CreateNoWindow = true,
                                    RedirectStandardOutput = false,
                                    RedirectStandardError = true,
                                    Arguments = script
                                };
            var imProcess = new Process();
            imProcess.StartInfo = startInfo;
            imProcess.Start();
            string outputMessage = imProcess.StandardError.ReadToEnd();
            imProcess.WaitForExit();
            imProcess.Close();
            if (outputMessage.Length > 0)
            {
                RaiseException(outputMessage);
            }
            //todo: was machen bei deadlock?
        }

        private void RaiseException(string message)
        {
            if (message.Contains("missing an image filename") || message.Contains("No such file or directory")) //todo: wird benötigt um fehlermeldung bei fehlendem load-pfad zu umgehen, geht das nicht auch schöner?
            {
                throw new IMFileNotFoundException("ImageMagick message: " + message);
            }
            else
            {
                throw new IMException("ImageMagick message: " + message);
            }
        }

        private string GetTempFilePath(string extension)
        {
            return Path.Combine(TempPath, Guid.NewGuid() + extension);
        }

        private string TempPath
        {
            get
            {
                if (null == tempPath)
                {
                    tempPath = Path.Combine(Path.GetTempPath(), "GIMS");
                    if (!Directory.Exists(tempPath))
                    {
                        Directory.CreateDirectory(tempPath);
                    }
                }
                return tempPath;
            }
        }
    }
}
